package com.validation.factory;

import org.springframework.stereotype.Service;

/**
 * @author Administrator
 */
@Service
public class EncryptionServiceImpl implements EncryptionService {

    final InitEncryptionFactory initEncryptionFactory;

    public EncryptionServiceImpl(InitEncryptionFactory initEncryptionFactory) {
        this.initEncryptionFactory = initEncryptionFactory;
    }

    @Override
    public String encrypt(Object value) {
        char[] chars = value.toString().toCharArray();
        StringBuilder encryptValue = new StringBuilder();
        for (char c : chars) {
            String ctr = String.valueOf(c);
            encryptValue.append(initEncryptionFactory.CD_MAP.containsKey(ctr) ? initEncryptionFactory.CD_MAP.get(ctr) : ctr);
        }
        return encryptValue.toString();
    }

    @Override
    public String decrypt(Object value) {
        StringBuilder decryptValue = new StringBuilder();
        String encrypt = value.toString();
        int lengths = encrypt.length() / initEncryptionFactory.Q;
        int start = 1;
        for (int i = 0; i < Integer.valueOf(lengths); i++) {
            String encryption = encrypt.substring(start, initEncryptionFactory.Q + start).toString();

            if (i == Integer.valueOf(lengths)) {
                encryption = String.join(encrypt.substring(start, (initEncryptionFactory.Q + initEncryptionFactory.R)-1));
            }
            start = start + initEncryptionFactory.Q;
            decryptValue.append(initEncryptionFactory.OD_MAP.containsKey(encryption) ? initEncryptionFactory.OD_MAP.get(encryption) : encryption);
        }
        return decryptValue.toString();
    }


}
